package com.dhcc.DRGsHosp.web.controller;

import com.dhcc.DRGsHosp.facade.DrgsService;
import com.dhcc.DRGsHosp.facade.MedicalRecordFacade;
import com.dhcc.DRGsHosp.facade.MedicalRecordNewFacade;
import com.dhcc.DRGsHosp.facade.MrDataImportService;
import com.dhcc.DRGsHosp.facade.dto.IndexCalDTO;
import com.dhcc.DRGsHosp.facade.dto.MedicalRecordDTO;
import org.codehaus.jackson.map.ObjectMapper;
import org.dayatang.utils.Page;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.openkoala.koala.commons.InvokeResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller("drgsHospWebController27")
@RequestMapping("/MedicalRecord")
public class MedicalRecordController {
		
	@Autowired
	private MedicalRecordFacade medicalRecordFacade;
	
	@Autowired
	private MedicalRecordNewFacade medicalRecordNewFacade;
	
	@Autowired
	private DrgsService drgsService;
	
	@Autowired
	private MrDataImportService mrDataImportServiceBean;
	
	@ResponseBody
	@RequestMapping("/add")
	public InvokeResult add(MedicalRecordDTO medicalRecordDTO) {
		return medicalRecordFacade.creatMedicalRecord(medicalRecordDTO);
	}
	
	@ResponseBody
	@RequestMapping("/update")
	public InvokeResult update(MedicalRecordDTO medicalRecordDTO) {
		return medicalRecordFacade.updateMedicalRecord(medicalRecordDTO);
	}
	
	@ResponseBody
	@RequestMapping("/pageJson")
	public Page<MedicalRecordDTO> pageJson(MedicalRecordDTO medicalRecordDTO, @RequestParam int page, @RequestParam int pagesize) {
		Page<MedicalRecordDTO> all = medicalRecordFacade.pageQueryMedicalRecord(medicalRecordDTO, page, pagesize);
		return all;
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	public InvokeResult remove(@RequestParam String ids) {
		String[] value = ids.split(",");
        String[] idArrs = new String[value.length];
        for (int i = 0; i < value.length; i ++) {
        					idArrs[i] = value[i];
			        				        }
        return medicalRecordFacade.removeMedicalRecords(idArrs);
	}
	
	@ResponseBody
	@RequestMapping("/get/{id}")
	public InvokeResult get(@PathVariable String id) {
		return medicalRecordFacade.getMedicalRecord(id);
	}


	@InitBinder
	public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    
        dateFormat.setLenient(false);    
        //CustomDateEditor 可以换成自己定义的编辑器。
        //注册一个Date 类型的绑定器 。
        binder.setAutoGrowCollectionLimit(Integer.MAX_VALUE);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

	}
    
    /**
     * 
     * @methodname    :findCaseList
     * @description   : 
     * @param         :
     * @author        :fulianxia
     * @return        :
     * @date          :2015年5月19日
     */
    @ResponseBody
    @RequestMapping(value = "/findCaseList", method = RequestMethod.POST)
    public InvokeResult findCaseList(IndexCalDTO dto,Boolean isAllUsers,@RequestParam int page, @RequestParam int pageSize,@RequestParam int sEcho) {
    	return medicalRecordFacade.findCaseList(dto,isAllUsers,page,pageSize, sEcho);
    }
   
    
    /**
	 * @methodname    :getMedicalRecordNum
	 * @description   :获取某年每月的病例数
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年7月7日
	 */
    @ResponseBody
    @RequestMapping(value = "/getMedicalRecordNum", method = RequestMethod.POST)
    public List<Map<String, Object>> getMedicalRecordNum(@RequestParam String year,@RequestParam String hospCode) {
    	return medicalRecordFacade.getMedicalRecordNum(year,hospCode);
    }
    /**
     * 
     *  getMedicalRecordYbNum.  
     *  @Description：获取某年每月的医保病例数
     *  @Author ZouYiyu
     *  @param year
     *  @return 
     *  @Date:2017年7月20日下午12:17:43
     */
    @ResponseBody
    @RequestMapping(value = "/getMedicalRecordYbNum", method = RequestMethod.POST)
    public List<Map<String, Object>> getMedicalRecordYbNum( String year, String hospCode) {
    	return medicalRecordFacade.getMedicalRecordYbNum(year,hospCode);
    }
    /**
     * @methodname    :exportData
     * @description   :导出首页数据到xml文件
     * @param         :
     * @author        :lileizheng
     * @return        :
     * @date          :2015年12月24日
     */
    @ResponseBody
    @RequestMapping(value = "dataExport")
    public InvokeResult dataExport(IndexCalDTO dto){
    	return medicalRecordFacade.dataExport(dto);
    }
    
    /**
	 * @methodname    :getLatestDate
	 * @description   :获取首页数据的最新日期
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2016年2月20日
	 */
    @ResponseBody
    @RequestMapping(value = "/getLatestDate", method = RequestMethod.POST)
    public String getLatestDate() {
    	return medicalRecordFacade.getLatestDate();
    }
    
    /**
	 * @methodname    :showMedicalrecordMapping
	 * @description   :读取xml标签
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2016年6月3日
	 */
    @ResponseBody
    @RequestMapping(value = "/showMedicalrecordMapping")
    public InvokeResult showMedicalrecordMapping() {
    	return medicalRecordNewFacade.showMedicalrecordMapping();
    }
    
    /**
	 * @methodname    :parseXmlTag
	 * @description   :解析xml标签
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2016年6月2日
	 */
    @ResponseBody
    @RequestMapping(value = "/parseXmlTag")
    public InvokeResult parseXmlTag(@RequestParam String xml) {
    	return medicalRecordNewFacade.parseXmlTag(xml);
    }
    
    /**
     * @methodname    :generateProp
     * @description   :生成properties文件
     * @param         :
     * @author        :WangTeng
     * @return        :
     * @date          :2016年6月3日
     */
    @SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping(value = "/generateProp")
    public InvokeResult generateProp(@RequestParam String prop) {
    	ObjectMapper objectMapper = new ObjectMapper();
    	Map<String, String> propMap = null;
		try {
			propMap = objectMapper.readValue(prop, Map.class);
		} catch (IOException e) {
			e.printStackTrace();
			return InvokeResult.failure("JSON解析失败");
		}
    	return medicalRecordNewFacade.generateProperties(propMap);
    }
    
    
    @ResponseBody
    @RequestMapping(value = "/getAllWard")
    public InvokeResult getAllWard() {
    	return medicalRecordFacade.getAllWard();
    }
    
    /**
     * @methodname    :universalImport
     * @description   :导入xml首页数据
     * @param         :
     * @author        :WangTeng
     * @return        :
     * @date          :2016年6月3日
     */
    List<String> filesPath = new ArrayList<String>();// 上传成功的文件路径
	@ResponseBody
    @RequestMapping(value = "/universalImport")
    public InvokeResult universalImport(HttpServletRequest request,HttpServletResponse response) {
		filesPath = new ArrayList<String>();
		//创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){
                        System.out.println("fileName:"+myFileName);  
                        //重命名上传后的文件名  
                        String fileName = "file"+new Date().getTime()+file.getOriginalFilename();  
                        //定义上传路径  
                        String path = request.getSession().getServletContext().getRealPath("/")+"upload";
                        File localFile = new File(path);
                        if (!localFile.exists()) {
							localFile.mkdirs();
						}
                        
                        localFile = new File(path + File.separatorChar + fileName);
                        try {
                        	//文件上传至服务器
							file.transferTo(localFile);
							filesPath.add(path + File.separatorChar + fileName);
						} catch (Exception e1) {
							e1.printStackTrace();
						} 
                    }
                }
            }
        }
		return InvokeResult.failure("");
    }
	
	@ResponseBody
	@RequestMapping(value="/universalImportComplete")
	public InvokeResult universalImportComplete(){
		String returnValue = "";
		for (String filePath : filesPath) {
			SAXReader reader = new SAXReader();
            Document document;
			try {
				document = reader.read(new File(filePath));
				String dataStr = document.asXML();
				System.out.println(dataStr);
				returnValue = drgsService.universalImport(dataStr);
                return InvokeResult.success(returnValue);
			} catch (DocumentException e) {
				e.printStackTrace();
				return InvokeResult.failure(e.getMessage());
			}
		}
        filesPath.clear();
        return InvokeResult.success();
	}
	


	@ResponseBody
	@RequestMapping(value="/importMrDataFromHIS")
	public InvokeResult importMrDataFromHIS(@RequestParam String dateFrom,@RequestParam String dateTo){
		mrDataImportServiceBean.importMrDataFromHIS(dateFrom, dateTo);
        return InvokeResult.success();
	}
	
}
